package com.example.safeassistan.login.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseActivity;
import com.example.safeassistan.common.MethodUtils;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.login.model.LoginModel;
import com.example.safeassistan.main.MainActivity;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.utile.SPUtils;
import com.example.safeassistan.utile.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 密码登录
 */
public class LoginPasswordActivity extends BaseActivity implements View.OnClickListener {
    private String TAG="LoginVerificationCodeActivity";
    private boolean isShow=false;
    private String phone = "";
    private EditText etLoginPhone,etLoginPassword;
    private ImageView ivClear;
    private TextView tvLogin,tvForgetpwd,tvCodeLogin;
    private String password = "";
    private ImageView ivEye;
    private ImageView ivBack,ivAgreement;

    private boolean isAgreement=false;
    public static void actionStart(Context context, String phone) {
        Intent intent = new Intent(context, LoginPasswordActivity.class);
        intent.putExtra("phone", phone);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_login_password;
    }

    @Override
    protected void initView() {
        phone = getIntent().getStringExtra("phone");
        etLoginPhone = findViewById(R.id.etLoginPhone);
        ivClear = findViewById(R.id.ivClear);
        tvForgetpwd=findViewById(R.id.tvForgetpwd);
        tvLogin = findViewById(R.id.tvLogin);
        ivClear.setOnClickListener(this);
        ivEye=findViewById(R.id.ivEye);
        ivBack=findViewById(R.id.ivBack);
        ivBack.setOnClickListener(this::onClick);
        ivEye.setOnClickListener(this::onClick);
        tvLogin=findViewById(R.id.tvLogin);
        etLoginPassword=findViewById(R.id.etLoginPassword);
        tvLogin.setOnClickListener(this::onClick);
        tvForgetpwd.setOnClickListener(this::onClick);
        tvCodeLogin=findViewById(R.id.tvCodeLogin);
        ivAgreement=findViewById(R.id.ivAgreement);
        ivAgreement.setOnClickListener(this::onClick);
        tvCodeLogin.setOnClickListener(this::onClick);
        etLoginPhone.setText(phone);
        etLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    phone = s.toString().trim();
                } catch (Exception e) {
                    phone = "";
                }
                checkInput();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.toString().length()>0){
                    ivClear.setVisibility(View.VISIBLE);
                }else {
                    ivClear.setVisibility(View.GONE);
                }
            }
        });

        etLoginPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    password = s.toString().trim();
                } catch (Exception e) {
                    password = "";
                }
                checkInput();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void checkInput() {
        if (phone.length()>0&&password.length()>0) {
            tvLogin.setClickable(true);
            tvLogin.setBackgroundResource(R.drawable.login_checked_bg);
            tvLogin.setTextColor(getResources().getColor(R.color.white));
        } else {
            tvLogin.setClickable(false);
            tvLogin.setBackgroundResource(R.drawable.login_unchecked_bg);
            tvLogin.setTextColor(getResources().getColor(R.color.white));
        }
    }

    @Override
    protected void initData() { }

    @Override
    public int getTitleBarType() {
        return TITLEBAR_NULL;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivAgreement:
                if(isAgreement){
                    isAgreement=false;
                    ivAgreement.setImageResource(R.mipmap.kj_icon_unselected);
                }else {
                    isAgreement=true;
                    ivAgreement.setImageResource(R.mipmap.kj_icon_selected);
                }
                break;
            case R.id.ivEye:
                //眼睛  代表密码可见不可见
                if(isShow){
                    //切换不可见密码
                    ivEye.setImageResource(R.mipmap.icon_no_eye);
                    //点一下可见
                    //设置代码可见 如果只设置TYPE_TEXT_VARIATION_PASSWORD则无效
                   etLoginPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    //改变状态值为假
                    isShow=false;
                }else{
                    //切换可见密码
                    ivEye.setImageResource(R.mipmap.icon_eye);
                    //点一下不可见
                    //设置代码不可见
                    etLoginPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    //改变状态值为真
                    isShow=true;
                }
                etLoginPassword.setSelection(etLoginPassword.getText().length());
                break;
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivClear://一键删除手机号
                etLoginPhone.setText("");
                phone="";
                break;
            case R.id.tvLogin:
                //密码登陆
               // if (isAgreement){
                    login();
//                }else {
//                    ToastUtil toastUtil=new ToastUtil(LoginPasswordActivity.this,R.layout.popu_success,"您需要同意安全防护相关协议！！",1);
//                    toastUtil.show();
//                }
                break;
            case R.id.tvForgetpwd:
                //忘记密码
                ForgetPassword.actionStart(getContext(),phone);
                break;
        }
    }

    /**
     * 登录
     */
    private void login() {
        if(phone==null||phone.equals("")){
            Toast.makeText(getContext(),"请填写手机号码",Toast.LENGTH_SHORT).show();
            return;
        }
        if(password==null||password.equals("")){
            Toast.makeText(getContext(),"请填写密码",Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject map = new JSONObject();
        try {
            map.put("username", phone);
            map.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(getContext()).doPost(UrlConstants.user_login, "登录中", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), LoginModel.class);
                        if (obj instanceof LoginModel) {
                            LoginModel model = (LoginModel) obj;
                            MethodUtils.loginAfter(LoginPasswordActivity.this, model.getResult().getUserInfo().getId(),
                                    model.getResult().getToken());
//                            UserData.create(LoginPasswordActivity.this).saveUserData(model.getResult().getUserInfo());
//                            MainActivity.actionStart(LoginPasswordActivity.this,0);
                           // SPUtils.setSharedBooleanData(LoginPasswordActivity.this,"isLogin",true);
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }
}